#include <iostream>
#include <fstream>
#include "contacts.pb.h"

using namespace std;

void AddPeopleInfo(contacts2::PeopleInfo* people)
{
    cout << "---------------新增联系人---------------" << endl;
    cout << "请输入联系人姓名：";
    string name;
    getline(cin,name);
    people->set_name(name);

    cout << "请输入联系人年龄：";
    int age;
    cin >> age;
    people->set_age(age);
    cin.ignore(256,'\n'); // 在输入年龄时可能会存在多出来的字符

    for(int i = 0;;i++)
    {
        cout << "请输入联系人电话" << i+1 << "(只输入回车完成电话新增)：";
        string number;
        getline(cin,number); // getline不会获取\n
        if(number.empty())
        {
            break;
        }
        contacts2::PeopleInfo_Phone* phone = people->add_phone(); // 用到的add函数
        phone->set_number(number);
    }




    cout << "--------------添加联系人成功-------------" << endl;
}

int main()
{
    contacts2::Contacts contacts;

    // 读取本地已存在联系人文件
    fstream input("contacts.bin",ios::in | ios::binary);
    if(!input)
    {
        cout << "contacts.bin not find,create new file!" <<endl; // 不存在文件
    }
    else if(!contacts.ParseFromIstream(&input))
    {
        cerr << "parse error!" << endl; // 反序列化失败
        input.close();
        return -1;
    }
    // 向通讯录中添加联系人
    AddPeopleInfo(contacts.add_contacts());

    // 将通讯录写入本地文件
    fstream output("contacts.bin",ios::out | ios::trunc | ios::binary);
    if(!contacts.SerializePartialToOstream(&output))
    {
        cerr << "write error!" << endl; // 序列化写入失败
        input.close();
        output.close();
        return -1;
    }
    cout << "write success!" <<endl;
    input.close();
    output.close();
    return 0;
}